<template>
  <Row>
    <Col span="6" order="1">
    <group_tree
      :tree_data="tree_data"
      @onLoadTreeData="loadTreeData"
      @onNodeClick="nodeClick"
      :isMultiple="false"></group_tree>
    </Col>
    <Col span="18" order="2">
    <Form ref="formInline" inline :style="{'padding-top': '20px'}">
      <FormItem>
        <Input type="text" placeholder="请输入姓名" size="large" style="width: 300px" clearable v-model="search_name">
        <Icon type="ios-person-outline" slot="prepend"></Icon>
        </Input>
      </FormItem>
      <FormItem>
        <Select style="width:300px" size="large" clearable v-model="search_sex">
          <Option v-for="(item, index) in sex" :value="item.value" :key="index">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem></FormItem>
      <FormItem>
        <DatePicker type="date" placeholder="创建时间-起始" style="width: 300px" clearable size="large"
                    @on-change="handle_search_start_data" editable>
        </DatePicker>
      </FormItem>
      <FormItem>
        <Icon type="minus-round"></Icon>
        <Icon type="minus-round"></Icon>
      </FormItem>
      <FormItem>
        <DatePicker type="date" placeholder="创建时间-结束" style="width: 300px" clearable size="large"
                    @on-change="handle_search_end_data" editable>
        </DatePicker>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="loadTableData" size="large">查询</Button>
      </FormItem>
    </Form>

    <!-- 导入用户 -->
    <Button type="info" icon="ios-redo" shape="circle" @click="import_btn_click">导入</Button>
    <!-- 导出用户 -->
    <Button type="info" icon="ios-redo" shape="circle" @click="export_btn_click">导出</Button>
    <!-- 增加用户 -->
    <Button type="info" icon="android-add-circle" shape="circle"
            @click="add_btn_click" :disabled="btn_disabled">增加
    </Button>

    <user_table
      :column_header="column_header"
      :table_data="table_data"
      :total_page="total_page"></user_table>

    <Page :total="total_page"
          style="float: right;padding-top: 10px;padding-bottom: 10px;"
          @on-change="change"
          @on-page-size-change="change"></Page>
    </Col>
  </Row>
</template>
<script>
  import group_tree from '../utils/tree_components_util'
  import user_table from '../utils/table_components_util'

  export default {
    data() {
      return {
        column_header: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '注册名',
            key: 'regname',
            align: 'left'
          },
          {
            title: '姓名',
            key: 'name',
            align: 'left',
            render: (h, params) => {
              return h('div', [
                h('Icon', {
                  props: {
                    type: 'person'
                  }
                }),
                h('strong', params.row.name)
              ]);
            }
          },
          {
            title: '性别',
            key: 'sex',
            align: 'center',
            render: (h, params) => {
              var icon = 'woman'
              var color = 'green'
              if (params.row.sex == '男') {
                icon = 'man'
                color = 'red'
              }
              return h('div', [
                h('Icon', {
                  props: {
                    type: icon,
                    size: '30',
                    color: color
                  }
                })
              ]);
            }
          },
          {
            title: '邮箱',
            key: 'email',
            align: 'left'
          },
          {
            title: '所属机构',
            key: 'gname',
            align: 'left'
          },
          {
            title: '创建日期',
            key: 'create_time',
            align: 'left'
          },
          {
            title: '状态',
            key: 'status',
            align: 'center',
            render: (h, params) => {
              var icon = 'heart-broken';
              var color = 'red';
              if (params.row.status == 1) {
                icon = 'heart';
                color = 'green';
              }
              return h('div', [
                h('Icon', {
                  props: {
                    type: icon,
                    size: '25',
                    color: color
                  }
                })
              ]);
            }
          },
          {
            title: '操作',
            key: 'handler',
            align: 'center',
            render: (h, params) => {
              const _this = this;
              return h('div', [
                h('Icon', {
                  props: {
                    type: 'edit',
                    size: '20'
                  },
                  style: {
                    marginRight: '5px',
                    cursor: "pointer"
                  },
                  on: {
                    click: () => {
                      this.$emit('childClickMenu', '基础数据', '学员管理', 'user_edit', {"id": params.row.id});
                    }
                  }
                }, 'View'),
                h('Icon', {
                  props: {
                    type: 'trash-a',
                    size: '20'
                  },
                  style: {
                    cursor: "pointer"
                  },
                  on: {
                    click: () => {
                      if (params.row.id == -1) {
                        this.$Notice.error({title: '警告', desc: '不可以删除管理员!'});
                        return;
                      }

                      this.$Modal.warning({
                        title: "注意",
                        content: "确定要删除数据吗？",
                        onOk: function () {
                          this.$http.delete(this.apiUrl() + 'user/delete/' + params.row.id, {
                            emulateJSON: true
                          }).then((response) => {
                            if (response.body.success) {
                              this.$Message.success(response.body.msg);
                              //_this表示的是vue的实例，是在上面定义的
                              //因为现在的作用域是在$Modal的这个模态窗口里
                              _this.loadTableData();
                            } else {
                              this.$Notice.error({title: '错误', desc: response.body.msg});
                            }
                          });
                        }
                      });
                    }
                  }
                }, 'Delete')
              ]);
            }
          }
        ],
        //查询，性别，select数据
        sex: [{
          value: "-1",
          label: "请选择性别"
        }, {
          value: "男",
          label: "男"
        }, {
          value: "女",
          label: "女"
        }],
        table_data: [],
        total_page: 0,
        current_page: 1,
        tree_data: [],
        //选中的机构树id
        current_group_id: '',
        //查询相关
        search_name: '',
        search_sex: '',
        search_start_data: '',
        search_end_data: '',
        btn_disabled: true
      }
    },
    components: {
      group_tree: group_tree,
      user_table: user_table
    },
    created: function () {
      //加载表格数据
      this.loadTableData();
      //加载树型结构数据
      this.loadTreeData();
    },
    methods: {
      handle_search_start_data: function (changeValue, date) {
        this.search_start_data = changeValue;
      },
      handle_search_end_data: function (changeValue, date) {
        this.search_end_data = changeValue;
      },
      /**
       * 点击分页，页数标签时调用的方法
       * @param page_num  页码改变的回调，返回改变后的页码
       */
      change: function (page_num) {
        this.current_page = page_num;
        this.loadTableData();
      },
      /**
       * 加载表格数据
       * @param page_num            查询条件：当前页
       * @param group_id            查询条件：机构id
       * @param search_name         查询条件：姓名
       * @param search_sex          查询条件：性别
       * @param search_start_data   查询条件：创建时间-起始
       * @param search_end_data     查询条件：创建时间-结束
       */
      loadTableData: function () {
        this.$http.post(this.apiUrl() + "user/grid/", {
          current_page: this.current_page,
          group_id: this.current_group_id,
          search_name: this.search_name,
          search_sex: this.search_sex,
          search_start_data: this.search_start_data,
          search_end_data: this.search_end_data
        }, {
          emulateJSON: true
        }).then((response) => {
          if (response.body.success) {
            this.table_data = response.body.grid;
            this.total_page = response.body.total_count;
          }
        });
      },
      /**
       * 异步加载树型数据的方法
       * @备注
       *        这个方法在页面加载成功后或者是异步加载树节点的时候都会调用
       *        只有在异步加载树节点时，两个参数才会有值，异步加载树节点是在tree_components_util.vue里调用的
       * @param item 选中节点信息
       * @param callback 执行 load-data 的第二个参数，将需要添加的数据传入
       */
      loadTreeData: function (item, callback) {
        var parentid = '-1';
        if (item != undefined) {
          parentid = item.id;
        }

        this.$http.post(this.apiUrl() + "group/tree/", {
          parent_id: parentid
        }, {
          emulateJSON: true
        }).then((response) => {
          /**
           * @备注:
           * 1. item如果不等于undefined,表示是树异步加载调用的，那么item即表示当前展开的节点
           * 2. 追加数据的时候其实是加开item节点的子节点，就应该用callback(response.body)追加数据
           * 3. 否则表示是第一次执行，那么直接this.tree_data = response.body给树的数据赋值
           */
          if (item != undefined) {
            callback(response.body);
          } else {
            this.tree_data = response.body;
          }
        });
      },
      /**
       * 点击机构树点节事件
       * @param node
       */
      nodeClick: function (node) {
        var groupid = node.id;
        this.current_group_id = groupid;
        this.loadTableData();
        this.btn_disabled = false;
      },
      /**
       * 点击导入用户按钮事件
       */
      import_btn_click: function () {
        const _this = this;
        this.$Modal.confirm({
          okText: "下载模板",
          onOk: function () {
            const url = this.apiUrl() + "user/downtemplate/";
            console.info("下载模板地址：" + url);
            //window.location.href = url;
            window.open(url);
          },
          render: (h) => {
            return h('Upload', {
              props: {
                type: "drag",
                action: _this.apiUrl() + "user/import/",
                'show-upload-list': false,
                'on-success': function (res, file) {
                  if (res && res.success) {
                    _this.$Message.success(res.msg);
                    this.$Modal.remove();
                    _this.loadTableData();
                  } else {
                    this.$Notice.error({title: '错误', desc: res.msg});
                  }
                  this.$Spin.hide();
                },
                'on-error': function (error, file, fileList) {
                  this.$Spin.hide();
                  this.$Notice.error({title: '错误', desc: error});
                },
                'on-progress': function () {
                  this.$Spin.show();
                }
              },
              on: {
                input: (val) => {
                  this.value = val;
                }
              }
            }, [
              h('div', {
                style: {
                  height: '100px'
                }
              }, [
                h('Icon', {
                  props: {
                    type: 'ios-cloud-upload',
                    size: '52',
                    color: '#3399ff'
                  }
                }),
                h('p', '点击此处或是将要上传的文件拖拽至此')
              ])
            ])
          }
        })
      },
      /**
       * 导出用户
       */
      export_btn_click: function () {
        const _this = this;
        const url = this.apiUrl() + "user/exportexcel"
        window.open(url);
      },
      /**
       * 增加用户
       */
      add_btn_click: function () {
        this.$emit('childClickMenu', '基础数据', '学员管理',
          'user_edit', {"group_id": this.current_group_id, "id": ''});
      }
    }
  }
</script>
<style scoped>

</style>
